<?php
namespace Admin\Controller;
use Think\Controller;
header('Access-Control-Allow-Origin:*');
header('Acess-Control-Allow-Methods:POST,GET');
class ShareController extends Controller {
	protected $db;
	protected function _initialize(){
		$this->db = D('share');
	}
	
	//异步接口
	public function ajax(){
		
		$data = $this->db->getAll();
		$this->ajaxReturn($data);		
	}
	
	public function ajaxJoin(){
		$data = $this->db->getJoin(I('id'));
		$this->ajaxReturn($data);
	}
	
    public function index(){
		$data = $this->db->getAll();

		$this->assign('data',$data);
        $this->display();    
    }
	
	public function del(){
		if($this->db->del()){
			$this->success('删除成功');
		}else{
			$this->error($this->db->getError());
		}
	}
	
	public function edit(){
		$id = I('id');
		$data = $this->db->getAll($id);
		
		if(IS_POST){
			if($this->db->edit()){
				$this->success('修改成功');
			}else{
				if(empty($this->db->getError())){
					$this->error('修改失败，值相同');
				}else{
					$this->error($this->db->getError());
				}
				
			}
		}
		
		$this->assign('id',$id);
		$this->assign('data',$data);
		$this->display();
	}
	
	public function pic(){
		$id = I('id');
		$data = $this->db->getAll($id);
		$data = $data['sharepic'];
		
		if(I('get.pid')){
			//删除旧文件
			$this->db->unnk($data);
			//清除sharepic字段 达到删除效果
			$_POST['sharePic'] = '';
			if($this->db->edit($id)){
				$this->success('删除成功');
			}else{
				$this->error($this->db->getError());
			}
		}
		
		if(IS_POST){
			$pic = $this->db->upload('sharePic','sharePic','封面上传失败');
			//删除旧文件
			$this->db->unnk(I('sharePic'));
				
			$_POST['sharePic'] = $pic[0];
			if($this->db->edit(I('id'))){
				$this->success('上传封面成功');
			}else{
				$this->error($this->db->getError());
			}
		}
		
		$this->assign('id',$id);
		$this->assign('data',$data);
		$this->display();
	}
	
	public function add(){
		if(IS_POST){
			if($this->db->m_add()){
				$this->success('添加成功');
			}else{
				$this->error($this->db->getError());
			}
		}else{
			$this->display();
		}
	}
}